#include "sprite.h"
#include <cstdio>

Sprite::Sprite()
: image(NULL),
frameWidth(0),
frameHeight(0),
numFrames(0)
{
}

Sprite::~Sprite()
{
	if (image!=NULL) {
		SDL_FreeSurface(image);
		image = NULL;
	}
}

void Sprite::initialize(char* filename, int frameWidth, int frameHeight, int numFrames)
{
	this->frameHeight = frameHeight;
	this->frameWidth = frameWidth;
	this->numFrames = numFrames;
	image = SDL_LoadBMP(filename);
	SDL_SetColorKey(image, SDL_SRCCOLORKEY, SDL_MapRGB(image->format, 255, 0, 255));
}

void Sprite::draw(int x, int y, int frame, SDL_Surface* screen)
{
	SDL_Rect src;
	src.x = frameWidth*frame;
	src.y = 0;
	src.w = frameWidth;
	src.h = frameHeight;

	SDL_Rect dest;
	dest.x = x;
	dest.y = y;
	dest.w = frameWidth;
	dest.h = frameHeight;

	SDL_BlitSurface(image, &src, screen, &dest);
}

int Sprite::nextFrame(int frame)
{
	frame++;
	if (frame >= numFrames)
		frame = 0;
	return frame;
}
